define([
    'require',
    'jquery',
    'api',
    'message',
    'blocksit',
    'picture_browser',
    'bigwe_component',
    'message',
    'constants',
], function(require, $) {
    var InterFace = require('api'),
        message = require('message'),
        pb = require('picture_browser'),
        bc = require('bigwe_component'),
        message = require('message'),
        route = require('constants');
    var returnFn = {},
        userGroup = [];

    var img_param = {
            url: InterFace.MYCOLLECTION.COLLECT_IMG_LS,
            data: {
                rt: 'collectImg',
                p: 1,
                l: 20,
            },
            callBack: param_list,
            completeBack: complete_back,
        },
        paging_sign = true,
        image_data = [];
    returnFn.init = function(data) {
        if (typeof data == 'undefined') {
            myAjax(img_param);
        }else if (typeof data == 'object') {
            userGroup = data;
        }else if (typeof data == 'string') {
            img_cg(img_id,data);
        }
    }

    var myAjax = function(options) {
        var defaults = {
            type: 'post', //请求的方法,默认为post
            beforefn: message.show('正在加载...'),
        };
        var opt = $.extend({}, defaults, options);
        $.ajax({
            type: opt.type,
            url: opt.url || '',
            data: opt.data || '',
            dataType: opt.dataType || 'json',
            before: function() {
                opt.beforefn || '';
            },
            success: function(data) {
                var data = (typeof data === 'string') ? $.parseJSON(data) : data;
                if ($.isFunction(opt.callBack)) {
                    opt.callBack(data);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus);
                console.log(XMLHttpRequest.status);
                console.log(XMLHttpRequest.readyState);
            },
            complete: function() {
                if ($.isFunction(opt.completeBack)) {
                    opt.completeBack();
                }
            }
        })
    }

    var content = $('.main_left');

    function param_list(data) {
        var list_html = '';
        var _total = data.data.total || '0';
        if (data.data.images.length == 0) {
            list_html = '<p><span class="glyphicon glyphicon-flash"></span>图片收藏夹为空</p>';
            $('#picture > .content_list').empty().append(list_html);
        } else {
            var arts = image_data = data.data.images;
            var _manager = content.find('.picture_batch').data('manager');
            for (var i in arts) {
                list_html += '<div class="picture_item' + (_manager ? '' : ' active') + '">' +
                    '<img src="/timthumb.php?w=225&src=' + arts[i].img_url + '" onerror="this.src=\'/Public/dev/images/wuyulantu.png\';"/>' +
                    '<div class="shade"> <p>' + (arts[i].title || '暂无标题') + '</p>' +
                    '<div class="icon_btn clearfix">';
                list_html += '<span class="iconfont icon-fenxiang pull-left">' +
                    '<div class="share"><a title="分享到QQ空间" class="qzone" href="javascript:void(0);"></a><a title="分享到新浪微博" class="sina" href="javascript:void(0);"></a>' +
                    '</div></span>' +
                    '<a class="iconfont icon-fasong pull-left" data-toggle="tooltip" title="发送" href="/sending?pic_cd=' + arts[i].cd + '" target="_blank"></a><span class="iconfont icon-huhuan pull-left move_group" data-toggle="tooltip" title="移动分组"></span><span class="pull-right cancel_collect">取消收藏</span></div>';
                list_html += '</div><div class="print_masking' + (_manager ? ' fade' : '') + '"><div class="backdrop"></div><span class="iconfont icon-zhengque"></span></div></div>';
            }

            $('.picture_list').empty().append(list_html).BlocksIt({
                numOfCol: 4,
                offsetX: 5,
                offsetY: 5,
            });
        }

        $('.altogether').find('.total_number').text(_total);
        if (paging_sign) {
            (_total > 20) ? ($('.paging').show(), paging(_total)) : ($('.paging').hide());
        }
    }

    function paging(total) {
        if (paging_sign && img_param.data.p != 1) {
            var current_page = img_param.data.p - 1;
        }
        $("#picture .paging").pagination(total, {
            num_edge_entries: 2,
            items_per_page: 20,
            current_page: current_page,
            prev_text: '上一页',
            next_text: '下一页',
            callback: function(_index, jq) {
                if (paging_sign) {
                    return;
                } else {
                    img_param.data.p = _index + 1;
                    myAjax(img_param);
                }
            }
        });
        paging_sign = false;
    }

    function complete_back() {
        // 判断图片加载状况，加载完成后回调
        isImgLoad(function() {
            message.hide();
            $('.picture_list').BlocksIt('reload').children().css({ opacity: '1' })
        });
    }

    var t_img; // 定时器
    var isLoad = true; // 控制变量

    // 判断图片加载的函数
    function isImgLoad(callback) {
        // 查找所有封面图，迭代处理
        $('.picture_list img').each(function() {
            // 找到为0就将isLoad设为false，并退出each
            if (this.height === 0) {
                isLoad = false;
                return false;
            }
        });
        // 为true，没有发现为0的。加载完毕
        if (isLoad) {
            clearTimeout(t_img); // 清除定时器
            // 回调函数
            callback();
            // 为false，因为找到了没有加载完成的图，将调用定时器递归
        } else {
            isLoad = true;
            t_img = setTimeout(function() {
                isImgLoad(callback); // 递归扫描
            }, 500); // 我这里设置的是500毫秒就扫描一次，可以自己调整
        }
    }

    /*搜索*/
    content.find('.search_btn').click(function() {
        var value = $("#search_text").val();
        var i = $('.nav_box > li.current').index();
        switch (i) {
            case 1:
                img_param.data.p = 1;
                img_param.data.key = value;

                paging_sign = true;
                myAjax(img_param);
                break;
        }
    });

    /*分组切换*/
    content.on('change', 'select.group_more', function() {
        if ($(this).val() != '') {
            $('.group_list').children().removeClass('green');
            $('.group_more').addClass('green');
            paging_sign = true;
            img_param.data.p = 1;
            img_param.data.cgid = $(this).val();
            myAjax(img_param);
        }
    });
    content.on('click', '.group_list > span', function() {
        if ($(this).hasClass('green')) {
            return false;
        }
        if ($('select.group_more').val() != '') {
            $('.group_more').removeClass('green');
            $('select.group_more').val('');
            $('select.group_more').selectpicker('refresh');
        }
        $(this).addClass('green').siblings().removeClass('green');
        paging_sign = true;
        img_param.data.p = 1;
        img_param.data.cgid = $(this).data('cgid');
        myAjax(img_param);
    });

    /*批量管理*/
    content.find('.picture_batch').click(function() {
        if ($(this).data('manager')) {
            $(this).data('manager', false);
            $(this).text('批量管理');
            $('.action_btn,.choice_num').addClass('hide');
            $('.article_grouping,.search,#upload_pictures,.altogether').removeClass('hide');
            content.find('.picture_item').addClass('active');
            content.find('.print_masking').removeClass('fade in');
            content.find('.choice_num').html('点击选择要批量操作的图片');
            content.find('.action_btn > button').attr('disabled', true);
            content.find('.picture_manager').removeClass('in');
        } else {
            $(this).data('manager', true);
            $(this).text('取消管理');
            $('.action_btn,.choice_num').removeClass('hide');
            $('.article_grouping,.search,#upload_pictures,.altogether').addClass('hide');
            content.find('.picture_item').removeClass('active');
            content.find('.print_masking').addClass('fade');
            content.find('.picture_manager').addClass('in');
        }
    });

    /*选中图片*/
    content.on('click', '.print_masking', function() {
        if ($(this).hasClass('in')) {
            $(this).removeClass('in');
        } else if (content.find('.print_masking.fade.in').length == 10) {
            message.showWarning('最多只能选择10张图片批量管理哦！', message.showTime);
            return;
        } else {
            $(this).addClass('in');
        }
        if (content.find('.print_masking.fade.in').length > 0) {
            content.find('.action_btn > button').removeAttr('disabled');
            content.find('.choice_num').html('已选<span class="green total_number">' + content.find('.print_masking.fade.in').length + '</span>张');
        } else {
            content.find('.action_btn > button').attr('disabled', true);
            content.find('.choice_num').html('点击选择要批量操作的图片');
        }
    })

    /*点击图片预览*/
    $('.picture_list').on('click', 'img', function() {
        pb.doPreviewPicture(image_data, undefined, $(this).parent().index());
    });

    /*分享*/
    var a, b, s, t = 0;
    s = {
        title: '',
    }, t = {
        jiathis: function(a, b) {
            window.open("http://www.jiathis.com/send/?webid=" + a + "&url=" + encodeURIComponent(b.url) + "&summary=" + encodeURIComponent(b.summary) + "&uid=2118247&pic=" + encodeURIComponent(b.img) + "&appkey=" + b.appkey);
        }
    }, $(".picture_list").on('click', '.share a', function(a) {
        var user_login = $('#user_login').val();
        var i = $(this).parents('.picture_item').index();

        if (user_login == '') {
            a.preventDefault();
            a.stopImmediatePropagation();
            $('#login-modal').modal('show');
            login.loginSuccessAndContinue = $.proxy(function() {
                $(this).trigger('click');
            }, this);

        } else {
            var _url = 'http://' + window.location.host + '/search/img_detail?picxx_cd=' + image_data[i].cd;
            a.stopPropagation();
            s.img = image_data[i].img_url;
            s.url = _url;
            s.summary = image_data[i].title == '' ? '分享图片' : image_data[i].title;
            share(a.target.className);
            a.preventDefault();
        }
    });

    function share(c) {
        switch (c) {
            case "qzone":
                s.appkey = 101286682;
                t.jiathis("qzone", s);
                break;
            case "sina":
                s.appkey = 2121870539;
                t.jiathis("tsina", s);
                break;
        }
    }

    /*移动分组*/
    content.on('click', '.action_group', groupmove);
    content.on('click', '.move_group', groupmove);

    var img_id;
    function groupmove(e) {
        e = e || event;
        e.stopPropagation();
        var groupData = userGroup;
        var groupsHtml = '';
        img_id = '';

        if ($(this).hasClass('action_group')) {
            $(".picture_list > div .print_masking").each(function() {
                if ($(this).hasClass('fade in')) {
                    var i = $(this).parents('.picture_item').index();
                    if (img_id.length > 1) {
                        img_id += ",";
                    }
                    img_id += image_data[i].cd;
                }
            });
        } else {
            var i = $(this).parents('.picture_item').index();
            img_id = image_data[i].cd;
            $(this).parents('.shade').addClass('in');
        }

        if (groupData.length < 1) {
            addGrouping(this, img_id);
            return;
        }
        groupsHtml += '<div image_id="' + img_id + '" class="category-tab pic_group" style="display: block;">';
        var cacl = 0;
        for (i in groupData) {
            if (cacl == 0) {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '"><div class="arrow"></div>' + groupData[i].group_name + '</div>';
                cacl++;
            } else {
                groupsHtml += '<div class="category" target_group="' + groupData[i].id + '">' + groupData[i].group_name + '</div>';
                cacl++;
            }
        }
        groupsHtml += '</div>';

        var left = 0,
            top = 0;

        var thisHeight = $(this).outerHeight(),
            thisWidth = $(this).outerWidth(),
            thisTop = $(this).offset().top,
            thisLeft = $(this).offset().left;
        if ($(this).hasClass('action_group')) {
            left = thisLeft + thisWidth - thisWidth / 2 + 58;
            top = thisTop + thisHeight - thisHeight / 2 - 20;
        } else {
            left = thisLeft + thisWidth - thisWidth / 2 + 20;
            top = thisTop + thisHeight - thisHeight / 2 - 20;
        }

        $('.pic_group').remove();
        $('body').append($(groupsHtml).css({
            left: left,
            top: top
        }));

        $(document).bind('click.category', function() {
            $('.pic_group').remove();
            $('.shade').removeClass('in');
            $(document).unbind('click.category');
        });
    };

    function addGrouping(obj) {
        var _this = $(obj);
        var type = event.srcElement.type;

        $("body").append('<div class="add_grouping">' +
            '<img src="' + route.resPath + '/images/Triangle-up.png">' +
            '<p>您还没有分组，请添加分组</p>' +
            '<input type="text" value="" maxlength="30" class="sure_val"><br/>' +
            '<button type="button" class="btn-success sure">确定</button>' +
            '<button type="button" class="btn-default btn_cancel" onclick="$(this).parent().remove()">取消</button>' +
            '</p>' +
            '</div>');
        $('.add_grouping').css({
            left: _this.offset().left - $('.add_grouping').width() / 2,
            top: _this.offset().top + $('.add_grouping').height() / 3,
        });

        $('.sure_val').focus();
        $('.sure_val').on('keyup', function(e) {
            e = e || event;
            if (e.keyCode == 13) {
                //判断是否按下的enter按键(回车键)
                $('.add_grouping > .sure').trigger('click');
            }
        });
        /**
         * 点击其他地方隐藏
         */
        $(document).bind('click.add_grouping', function(e) {
            var e = e || window.event; //浏览器兼容性 
            var elem = e.target || e.srcElement;
            while (elem) { //循环判断至跟节点，防止点击的是div子元素 
                if (elem.className && elem.className == 'add_grouping') {
                    return;
                }
                elem = elem.parentNode;
            }

            $(".add_grouping").remove(); //点击的不是div或其子元素 
            $('.shade').removeClass('in');
            $(document).unbind("click.add_grouping");
        });
    };

    $(document).on('click', '.pic_group .category', img_cg);

    function img_cg(s, d) {
        $('.shade').removeClass('in');
        if (d) {
            var cd = s,
                cgid = d;
        } else {
            var cd = $(this).parent().attr('image_id'),
                cgid = $(this).attr('target_group');
        }

        $.ajax({
            type: 'post',
            url: InterFace.MYCOLLECTION.CHANGE_GROUP,
            data: {
                rt: 'collectImg',
                cgid: cgid,
                cd: cd,
            },
            success: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {
                    message.show('操作成功！', message.showTime);
                    group_id();
                    if ($(".group_list > span.green").text() != '全部') {
                        paging_sign = true;
                        myAjax(img_param);
                    }
                } else {
                    message.showWarning('您还没有分组或者该图文已存在您唯一分组中', message.showTime);
                }
            }
        })
    };

    /*分组文章数同步*/
    function group_id() {
        $.ajax({
            type: 'post',
            url: InterFace.MYCOLLECTION.GET_GROUP,
            data: {
                rt: 'collectImg'
            },
            success: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {
                    var arts = data.data;
                    for (var i in arts) {
                        $('[groupid=\"' + arts[i].id + '\"]').find('.battery-number').text(arts[i].group_num);
                    }
                }
            }
        });
    }

    /*取消收藏*/
    $('.picture_list').on('click', '.cancel_collect', function() {
        var _this = $(this);
        var i = _this.parents('.picture_item').index();
        var grouping_id = image_data[i].cd;
        _this.parents('.shade').addClass('in');

        bc.deleteConfirmShowBottom({
            obj: this,
            text: '确认要取消收藏吗？',
            fun: function() {
                _this.parents(".picture_item").remove();

                deletedata(grouping_id);
            },
            cancel: function() {
                _this.parents('.shade').removeClass('in');
            }
        });
    });

    $('.tool_s').on('click','.action_delete',function() {
        var object = "";
        $(".picture_list > div .print_masking").each(function() {
            if ($(this).hasClass('fade in')) {
                var i = $(this).parents('.picture_item').index();
                if (object.length > 1) {
                    object += ",";
                }
                object += image_data[i].cd;
            }
        });

        bc.deleteConfirmShowBottom({
            obj: this,
            text: '确认要取消收藏吗？',
            fun: function() {
                $('.print_masking.fade.in').parent().remove();
	            content.find('.choice_num').html('点击选择要批量操作的图片');
                deletedata(object);
            }
        });
    });

    function deletedata(grouping_id) {
        $.ajax({
            type: 'post',
            url: InterFace.IMG_BROWSE.DO_COLLECT_IMG,
            data: {
                cd: grouping_id
            },
            success: function(data) {
                var data = typeof data === 'string' ? $.parseJSON(data) : data;
                if (data.ret == 0) {
                    if ($('.picture_list > div').length == 0) {
                        paging_sign = true;
                        if (img_param.data.p != 1) {
                            img_param.data.p -= 1;
                        }
                    }
                    myAjax(img_param);
                    group_id();
                    message.show('取消收藏成功！', message.showTime);
                    $('.action_btn > button').prop('disabled', true);
                }
            }
        });
    };

    return returnFn;
});
